CSS背景颜色设置透明度的两种方法(8位hex和rgba) 您所在的位置:网站首页 rgb 8位 16位 32位 CSS背景颜色设置透明度的两种方法(8位hex和rgba)

CSS背景颜色设置透明度的两种方法(8位hex和rgba)

2023-10-23 01:51| 来源: 网络整理| 查看: 265

目录 一、 6位HEX转RGBA二、8位HEX 在写微信小程序的时候,有个需求是按背景颜色 background-color要设透明度0.85,让背景图片 background-image透一点出来,而且 background-color的值是后端传过来的动态数据,背景颜色动态改变,UI同学给的数据全是6位HEX,需要我自己设置透明度。

设置透明度首先会想到用opacity,但 opacity 会把被设置的元素及其子元素同时设置为同一个透明度,我需要子元素不透明,opacity就不能用了。

接下来讲两个实际可用性比较高的方法,以下两种方法都在chrome和微信小程序上亲测可用:

一、 6位HEX转RGBA

rgba的alpha值可以设透明度而不影响子元素。但是UI同学给的几百个数据都是6位hex,所以需要我自己手动把6位hex格式转成rgb格式,再加上alpha值0.85写成rgba(x, x, x, 0.85)。

其实hex转rgb就是十进制转十六进制,最简单的办法就是用JS原生的parseInt() 函数帮我们做转换。以下是MDN文档对parseInt的说明:

parseInt(string, radix) 将一个字符串 string 转换为 radix 进制的整数, radix 为介于2-36之间的数。 … 如果 radix 是 undefined、0或未指定的,JavaScript会假定以下情况:

如果输入的 string以 "0x"或 “0x”(一个0,后面是小写或大写的X)开头,那么radix被假定为16,字符串的其余部分被解析为十六进制数。如果输入的 string以 “0”(0)开头, radix被假定为8(八进制)或10(十进制)。具体选择哪一个radix取决于实现。ECMAScript 5 澄清了应该使用 10 (十进制),但不是所有的浏览器都支持。因此,在使用 parseInt 时,一定要指定一个 radix。如果输入的 string 以任何其他值开头, radix 是 10 (十进制)。

根据说明,我们有两种方式hex转rgb,可以parseInt(hex.slice(x, x+2), 16); 也可以parseInt('0x'+hex.slice(x, x+2))。最后再设置0-1或者百分数的alpha值,就顺利转好rgba了,以下是完整代码:

// 颜色格式 hex 转 rgba const hexToRgba = (bgColor) => { let color = bgColor.slice(1); // 去掉'#'号 let rgba = [ parseInt('0x'+color.slice(0, 2)), parseInt('0x'+color.slice(2, 4)), parseInt('0x'+color.slice(4, 6)), 0.85 ]; return 'rgba(' + rgba.toString() + ')'; };

最后的Array.prototype.toString() 函数不带参数指定分隔号,会默认用逗号分隔,正好是我们想要的。

二、8位HEX

要不是这个需求,我还不知道CSS Color Module Level 4标准早在2014年就推出8位hex和4位hex来支持设置alpha值,以实现hex和rgba的互转。这个办法可比6位HEX转RGBA简洁多了,先来简单解释一下: 8位hex是在6位hex基础上加后两位来表示alpha值,00表示完全透明,ff表示完全不透明。

8 digits The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where ‘00’ represents a fully transparent color and ‘ff’ represent a fully opaque color. In other words, #0000ffcc represents the same color as rgb(0 0 100% / 80%) (a slightly-transparent blue).

同理,4位hex是在3位hex基础上加后一位来表示alpha值,0表示完全透明,f表示完全不透明。

4 digits This is a shorter variant of the 8-digit notation, “expanded” in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where 0 represents the minimum value and f represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.

比如以下三种写法表示的是同个颜色:

.element { background: rgba(0, 255, 0, 0.53); // rgba background: #0f08; //4位hex background: #00ff0088; //8位hex }

以下是摘自文章8-Digit Hex Codes?的alpha值的十进制和十六进制对照表:

Alpha %HexRgb 255100%FF25595%F224290%E623085%D921780%CC20475%BF19170%B317965%A616660%9915355%8C14050%8012845%7311540%6610235%598930%4D7725%406420%335115%263810%1A265%0D130%000

根据以上表,我在6位HEX后面加上字符串D9就能轻松搞定背景颜色设置透明度85%的需求了~

觉得有用的请点个赞,谢谢大家的观看~转载请带本文链接,谢谢!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有